/**
 * 
 */
package ru.olympus.antonyhands.ao.client.widgets;

import ru.olympus.antonyhands.ao.client.AOHelperServiceAsync;
import ru.olympus.antonyhands.ao.client.widgets.TreeTable.TreeTableDataSource;
import ru.olympus.antonyhands.ao.shared.item.EItemParentType;
import ru.olympus.antonyhands.ao.shared.item.EItemsViewType;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * @author AntonyHands
 * @since 01.03.2012
 */
public class CheapestWayToGetItem extends VerticalPanel {

	private AOHelperServiceAsync _service;
	private ItemCategoriesListBox _itemCategories;
	private ItemsListBox _items;
	private ItemHierarchyMarketPriceUpdatePanel _marketPricesUpdater;
	private TreeTable _craftTable;

	public CheapestWayToGetItem(AOHelperServiceAsync service) {
		_service = service;

		Grid table = new Grid(2, 2);
		add(table);

		table.setHTML(0, 0, "Категория");
		table.setHTML(1, 0, "Предмет");

		_itemCategories = new ItemCategoriesListBox(_service);
		table.setWidget(0, 1, _itemCategories);

		_items = new ItemsListBox(_service, _itemCategories, EItemParentType.ITEM_CATEGORY, EItemsViewType.ALPHABETICAL);
		table.setWidget(1, 1, _items);

		_craftTable = new TreeTable();
//		_craftTable.setVisible(false);
		add(_craftTable);

		_marketPricesUpdater = new ItemHierarchyMarketPriceUpdatePanel(_service, _items)
		{
			@Override
			public void onSuccessfulPricesUpdate() {
				super.onSuccessfulPricesUpdate();

				_service.getItemCraftDS(_items.getCurrentValueCode(), 
						new AsyncCallback<TreeTable.TreeTableDataSource>() {
					
							@Override
							public void onSuccess(TreeTableDataSource result) {
								_marketPricesUpdater.setVisible(false);
								_craftTable.setVisible(true);
								_craftTable.setDataSource(result);
							}

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub
								Window.alert("Error: " + caught.getMessage());
							}
						});
			}

			@Override
			protected void repaint() {
				setVisible(true);
				_craftTable.setVisible(false);
				super.repaint();
			}
		};
		add(_marketPricesUpdater);
	}
}
